"use client";

import { useState, useRef, useEffect } from "react";
import { useParams, usePathname } from "next/navigation";

interface Language {
  code: string;
  name: string;
  flag: string;
  nativeName: string;
}

const languages: Language[] = [
  { code: "en", name: "English", flag: "🇺🇸", nativeName: "English" },
  { code: "zh", name: "Chinese", flag: "🇨🇳", nativeName: "中文" },
  { code: "ja", name: "Japanese", flag: "🇯🇵", nativeName: "日本語" },
];

export const LanguageSwitcher = () => {
  const params = useParams();
  const pathname = usePathname();
  const currentLng = (params?.lng as string) || "en";
  const [isOpen, setIsOpen] = useState(false);
  const dropdownRef = useRef<HTMLDivElement>(null);

  const currentLanguage = languages.find((lang) => lang.code === currentLng) || languages[0];

  // 点击外部关闭下拉菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
        setIsOpen(false);
      }
    };

    document.addEventListener("mousedown", handleClickOutside);
    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  // 生成切换语言后的路径
  const getLanguageUrl = (langCode: string) => {
    if (!pathname) return `/${langCode}`;
    
    // 替换路径中的语言代码
    const segments = pathname.split("/").filter(Boolean);
    if (segments.length > 0 && languages.some((lang) => lang.code === segments[0])) {
      segments[0] = langCode;
      return `/${segments.join("/")}`;
    }
    
    return `/${langCode}`;
  };

  return (
    <div className="relative" ref={dropdownRef}>
      {/* 触发按钮 */}
      <button
        onClick={() => setIsOpen(!isOpen)}
        className="flex items-center gap-2 rounded-xl px-3 py-2 text-sm font-medium text-gray-700 transition-all hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-800"
        aria-label="Select language"
        aria-expanded={isOpen}
      >
        <span className="text-lg">{currentLanguage.flag}</span>
        <span className="hidden sm:inline text-sm font-semibold">{currentLanguage.code.toUpperCase()}</span>
        <svg
          className={`h-4 w-4 transition-transform duration-200 ${isOpen ? "rotate-180" : ""}`}
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 9l-7 7-7-7" />
        </svg>
      </button>

      {/* 下拉菜单 */}
      <div
        className={`absolute right-0 top-full mt-2 w-48 rounded-2xl bg-white py-2 shadow-2xl border border-gray-100 dark:bg-gray-800 dark:border-gray-700 transition-all duration-200 origin-top ${
          isOpen ? "opacity-100 scale-100 visible" : "opacity-0 scale-95 invisible"
        }`}
      >
        {languages.map((lang) => {
          const isActive = lang.code === currentLng;
          
          return (
            <a
              key={lang.code}
              href={getLanguageUrl(lang.code)}
              onClick={() => setIsOpen(false)}
              className={`flex items-center gap-3 px-4 py-3 mx-2 rounded-xl transition-all ${
                isActive
                  ? "bg-gradient-to-r from-blue-500 to-purple-600 text-white font-medium shadow-lg shadow-blue-500/25"
                  : "text-gray-700 hover:bg-gray-100 dark:text-gray-300 dark:hover:bg-gray-700"
              }`}
            >
              <span className="text-xl">{lang.flag}</span>
              <div className="flex-1 min-w-0">
                <div className={`text-sm font-medium ${isActive ? "text-white" : ""}`}>
                  {lang.nativeName}
                </div>
                <div className={`text-xs ${isActive ? "text-white/80" : "text-gray-500 dark:text-gray-400"}`}>
                  {lang.name}
                </div>
              </div>
              {isActive && (
                <svg className="h-5 w-5 text-white flex-shrink-0" fill="currentColor" viewBox="0 0 20 20">
                  <path
                    fillRule="evenodd"
                    d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z"
                    clipRule="evenodd"
                  />
                </svg>
              )}
            </a>
          );
        })}
      </div>
    </div>
  );
};
